<script setup>
import {onMounted, ref} from "vue";
import {doGet, doPost} from "../util/request.js";
  import {showMessage} from "../util/message.js";
  import {TOKEN_NAME} from "../util/constants.js";

  // 创建表单响应式登录用户对象
  const loginUser = ref({})
  // 创建登录表单响应式验证规则对象
  const loginFormRules = ref({
    loginAct: [
      {required: true, message: '请输入登录帐号', trigger: 'blur'},
      {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
    ],
    loginPwd: [
      {required: true, message: '请输入登录密码', trigger: 'blur'},
      {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
    ]
  })
  // 创建提交表单验证响应式对象
  const loginRuleFormRef = ref({})

  // 提交登录表单
  const submitLogin = (formEl)=>{
    if (!formEl) return
    formEl.validate(valid => {
      if (valid) {
        console.log('提交用户登录请求!')
        let rememberMe = loginUser.value.rememberMe === undefined?false:loginUser.value.rememberMe
        // 准备登录请求的表单对象参数
        const formData = new FormData()
        formData.append('loginAct', loginUser.value.loginAct)
        formData.append('loginPwd', loginUser.value.loginPwd)
        formData.append('rememberMe', rememberMe)
        const params = new URLSearchParams(formData)
        console.log("用户登录请求参数：",params.toString())
        // 发送登录请求
        doPost('/api/login', formData).then((resp)=>{
          if (resp.data.code === 200) {
            // 获取令牌token
            let token = resp.data.data
            // 登录成功 -> 将令牌TOKEN存放到前端

            // 清除前端存储的令牌
            sessionStorage.removeItem(TOKEN_NAME)
            localStorage.removeItem(TOKEN_NAME)

            // 判断用户是否选择“记住我”
            if (rememberMe) {
              // 选择“记住我”，保存到本地存储
              localStorage.setItem(TOKEN_NAME,token)
            } else {
              // 没有选择“记住我”，保存到会话存储
              sessionStorage.setItem(TOKEN_NAME,token)
            }

            // 跳转至管理平台的首页面
            window.location.href = '/dashboard'

          } else {
            showMessage(resp.data.message, 'error');
          }
        });
      }
    })
  }

  // 重置表单
  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
  }

  onMounted(() => {
    console.log('登录页面加载了')
    // 从本地存储中获取令牌TOKEN
    let token = localStorage.getItem(TOKEN_NAME)
    // 判断令牌是否有值
    if (token) {
      // 有值，说明用户之前选中了“记住我”，可以自动的登录
      doGet('/api/user/isLogin',{})
          .then(resp => {
            if (resp.data.code === 200) {
              window.location.href = '/dashboard'
            }
          })
    }
  })
</script>

<template>

  <el-container>
    <!--    左侧：侧边拦容器-->
    <el-aside width="200px">
      <img alt="登录图片" class="login-img" src="../assets/loginBox.svg"/>
      <div class="login-text">欢迎使用动力云客系统</div>
    </el-aside>

    <!--    右侧：主要区域容器-->
    <el-main>
      <h3 style="margin-top: 150px">欢迎登录</h3>

      <el-form
          ref="loginRuleFormRef"
          style="max-width: 600px;margin-left: 25%;margin-right: 25%"
          :model="loginUser"
          :rules="loginFormRules"
          label-width="auto"
          class="demo-ruleForm">

        <el-form-item label="帐号" prop="loginAct">
          <el-input v-model="loginUser.loginAct" />
        </el-form-item>

        <el-form-item label="密码" prop="loginPwd">
          <el-input type="password" v-model="loginUser.loginPwd" />
        </el-form-item>

        <el-form-item label=" ">
          <el-button type="primary" @click="submitLogin(loginRuleFormRef)">登录</el-button>
          <el-button @click="resetForm(loginRuleFormRef)">重置</el-button>
        </el-form-item>

        <el-form-item label=" ">
          <el-checkbox v-model="loginUser.rememberMe" name="type">记住我</el-checkbox>
        </el-form-item>
      </el-form>

    </el-main>

  </el-container>
</template>

<style scoped>
.el-aside{
  background-color: #535bf2;
  width: 40%;
  height: calc(100vh);
  text-align: center;
}
.login-text{
  color: aliceblue;
  font-size: 30px;
}
.login-img{
  width: 80%;
  margin-top: 75px;
}
.el-main{
  text-align: center;
}
</style>